package tcp

import (
	"gomonitor-server/src/config"
	"gomonitor-server/src/db"
	"gomonitor-server/src/mylog"
	"gomonitor-server/src/tcp/connectioncount"
	"gomonitor-server/src/tcp/types"
	"net"
	"strconv"
)

var listener net.Listener
var closed bool = false

func Stop() {
	if listener != nil {
		defer func(listener net.Listener) {
			err := listener.Close()
			if err != nil {
				mylog.Logger.Fatal("Error Close the server:", err)
			}
			closed = true
		}(listener)
	}
}

func Start(appCfg *config.Config) {
	tcpPort := appCfg.App.TcpPort
	if tcpPort == 0 {
		tcpPort = 45625
		mylog.Logger.Info("tcp端口没有配置,使用默认端口:" + strconv.Itoa(tcpPort))
	}
	listener, err := net.Listen("tcp", ":"+strconv.Itoa(tcpPort))
	if err != nil {
		mylog.Logger.Fatal("Error starting the server:", err)
	}

	mylog.Logger.Info("服务器正常启动，监听端口是 :" + strconv.Itoa(tcpPort))

	db.UpdateErrorHostState()
	go func() {
		for {
			if closed {
				break
			}
			conn, err := listener.Accept()
			if err != nil {
				mylog.Logger.Warningf("接收监听失败,跳过:%s", err.Error())
				continue
			}
			mylog.Logger.Infof("TCP客户端%s成功连接", conn.RemoteAddr().String())
			host, port, err := net.SplitHostPort(conn.RemoteAddr().String())
			if err != nil {
				mylog.Logger.Error("error reading from tcp: ", err)
				return
			}
			portInt, err := strconv.ParseUint(port, 10, 32)
			if err != nil {
				portInt = 0
			}
			connectioncount.AddConnection(conn)
			db.RecordConnectLog(host, int(portInt), 1)
			go handleConnection(types.MSG_FROM_CLIENT, conn)
		}
	}()
}
